package com.wendy.admin.controller;

import com.wendy.admin.api.domain.LoginSysUser;
import com.wendy.admin.api.model.LoginUser;
import com.wendy.admin.entity.SysUser;
import com.wendy.admin.errorcode.ProFileError;
import com.wendy.admin.service.ISysUserService;
import com.wendy.common.core.utils.StringUtils;
import com.wendy.common.core.utils.file.MimeTypeUtils;
import com.wendy.common.log.annotation.Log;
import com.wendy.common.log.enums.BusinessType;
import com.wendy.common.web.controller.BaseController;
import com.wendy.common.web.utils.file.FileTypeUtils;
import com.wendy.custom.security.service.TokenService;
import com.wendy.custom.security.utils.SecurityUtils;
import com.wendy.file.RemoteFileService;
import com.wendy.file.domain.SysFile;
import com.wendy.utils.spring.MapstructUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @author wendy
 */
@RestController
@RequestMapping("/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 个人信息
     */
    @GetMapping
    public Map<String,Object> profile() {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        Map<String,Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(username));
        ajax.put("postGroup", userService.selectUserPostGroup(username));
        return ajax;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public boolean updateProfile(@RequestBody SysUser user) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        LoginSysUser currentUser = loginUser.getSysUser();
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhonenumber(user.getPhonenumber());
        currentUser.setSex(user.getSex());
        SysUser sysUser = MapstructUtils.convert(currentUser, SysUser.class);
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(sysUser)) {
            ProFileError.EDIT_USER_PHONE_ERROR.formatFire(loginUser.getUsername());
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(sysUser)) {
            ProFileError.EDIT_USER_EMAIL_ERROR.formatFire(loginUser.getUsername());
        }
        if (userService.updateUserProfile(sysUser) == 0) {
            ProFileError.EDIT_USER_INFO_ERROR.fire();
        }
        // 更新缓存用户信息
        tokenService.setLoginUser(loginUser);
        return true;
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public Boolean updatePwd(String oldPassword, String newPassword) {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            ProFileError.EDIT_PASSWORD_OLD_ERROR.fire();
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            ProFileError.EDIT_PASSWORD_EQUAL_ERROR.fire();
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(username, newPassword) == 0) {
            ProFileError.EDIT_PASSWORD_ERROR.fire();
        }
        // 更新缓存用户密码
        LoginUser loginUser = SecurityUtils.getLoginUser();
        loginUser.getSysUser().setPassword(newPassword);
        tokenService.setLoginUser(loginUser);
        return true;
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public Map<String, Object> avatar(@RequestParam("avatarfile") MultipartFile file) {
        if (file.isEmpty()) {
            ProFileError.FILE_UPLOAD_ERROR.fire();
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String extension = FileTypeUtils.getExtension(file);
        if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
            ProFileError.FILE_FORMAT_ERROR.formatFire(Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION));
        }
        SysFile fileResult = remoteFileService.upload(file);
        if (StringUtils.isNull(fileResult)) {
            ProFileError.FILE_SERVER_ERROR.fire();
        }
        String url = fileResult.getUrl();
        if (!userService.updateUserAvatar(loginUser.getUsername(), url)) {
            ProFileError.FILE_UPLOAD_ERROR.fire();
        }
        Map<String, Object> map = new HashMap<>(8);
        map.put("imgUrl", url);
        // 更新缓存用户头像
        loginUser.getSysUser().setAvatar(url);
        tokenService.setLoginUser(loginUser);
        return map;
    }
}
